// 云函数入口文件
const cloud = require('wx-server-sdk');
cloud.init({
    // API 调用都保持和云函数当前所在环境一致
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()


exports.main = async(event, context) => {
    const wxContext = cloud.getWXContext();
    let { type } = event
    try {
        let result = await db.collection("myWatch").where({
            openid: wxContext.OPENID
        }).get();
        if (result.data && result.data.length > 0) {
            let data = result.data[0];
            let _id = data._id
            let hasWatch = data[type].find(val => val == event.id);
            if (hasWatch) { //原本已经这个项目的ID
                return {
                    isChange: false
                }
            } else {
                data[type].push(event.id);
                return await db.collection('myWatch').doc(_id).update({
                    data: {
                        [type]:data[type]
                    }
                })
            }
        } else {
            return await db.collection('myWatch').add({
                data: {
                    openid: wxContext.OPENID,
                    watch:type=='watch'?[event.id]:[],
                    benefit:type=='benefit'?[event.id]:[]
                }
            })
        }
    } catch (e) {
        console.error(e)
    }
}

// 云函数入口函数
// exports.main = async(event, context) => {
//     const wxContext = cloud.getWXContext()
//     return {
//         event,
//         openid: wxContext.OPENID,
//         appid: wxContext.APPID,
//         unionid: wxContext.UNIONID,
//     }
// }